package service;

import dao.*;
import pojo.Admin;
import pojo.Bed;
import pojo.CheckInRecord;
import pojo.CheckOutRecord;
import utils.JDBCUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.jar.JarEntry;

public class CheckOutRecordServiceImpl implements CheckOutRecordService{
    private CheckOutRecordDao dao = new CheckOutRecordDaoImpl();
    private CheckInRecordDao checkInRecordDao = new CheckInRecordDaoImpl();
    private BedDao bedDao = new BedDaoImpl();
    private Connection connection = null;

    @Override
    public ArrayList<CheckOutRecord> findAll() {
        return dao.findAll();
    }

    @Override
    public ArrayList<CheckOutRecord> findDate(Date begin, Date end) {
        ArrayList<CheckOutRecord> list = dao.findAll();
        ArrayList<CheckOutRecord> checkOutRecords = new ArrayList<CheckOutRecord>();
        for (CheckOutRecord checkOutRecord : list) {
            if((checkOutRecord.getActual_cherk_out_time().after(begin)&&checkOutRecord.getActual_cherk_out_time().before(end))||checkOutRecord.getActual_cherk_out_time().equals(begin)||checkOutRecord.getActual_cherk_out_time().equals(end)){
                checkOutRecords.add(checkOutRecord);
            }
        }
        return checkOutRecords;
    }

    @Override
    public CheckOutRecord findById(Integer stuId) {
        return dao.findById(stuId);
    }

    @Override
    public int insert(CheckOutRecord checkOutRecord) {
        try {
            //增加退租记录
            connection = JDBCUtils.getConnection();
            connection.setAutoCommit(false);
            int row1 = dao.insert(connection,checkOutRecord);

            //更改床铺状态
            Bed bed = bedDao.findById(checkOutRecord.getDormId(),checkOutRecord.getBedId());
            int row2 = bedDao.update(connection,bed);

            //删除入住记录
            CheckInRecord checkInRecord = checkInRecordDao.findById(checkOutRecord.getStuId());
            int row3 = checkInRecordDao.delete(checkInRecord);
            connection.commit();
            return row1+row2+row3;
        } catch (SQLException e) {
            e.printStackTrace();
            try {
                connection.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }finally {
            try {
                connection.setAutoCommit(true);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public int update(CheckOutRecord checkOutRecord) {
        return dao.update(checkOutRecord);
    }

    @Override
    public int delete(CheckOutRecord checkOutRecord) {
        return dao.delete(checkOutRecord);
    }
}
